from . import db
from datetime import datetime

class Material(db.Model):
    __tablename__ = 'materials'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    code = db.Column(db.String(50), unique=True)  # 物料编码
    category = db.Column(db.String(50))  # 物料分类
    unit = db.Column(db.String(20))  # 单位：个、台、米、公斤等
    specification = db.Column(db.Text)  # 规格说明
    stock_quantity = db.Column(db.Float, default=0)  # 库存数量
    min_stock = db.Column(db.Float, default=0)  # 最小库存
    unit_price = db.Column(db.Float)  # 单价
    supplier = db.Column(db.String(100))  # 供应商
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'code': self.code,
            'category': self.category,
            'unit': self.unit,
            'specification': self.specification,
            'stock_quantity': self.stock_quantity,
            'min_stock': self.min_stock,
            'unit_price': self.unit_price,
            'supplier': self.supplier,
            'is_active': self.is_active,
            'is_low_stock': self.stock_quantity <= self.min_stock if self.min_stock else False,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<Material {self.name}>'

class MaterialUsage(db.Model):
    __tablename__ = 'material_usages'

    id = db.Column(db.Integer, primary_key=True)
    material_id = db.Column(db.Integer, db.ForeignKey('materials.id'), nullable=False)
    work_order_id = db.Column(db.Integer, db.ForeignKey('work_orders.id'), nullable=True)  # 允许为空，支持非工单使用
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    quantity = db.Column(db.Float, nullable=False)
    usage_type = db.Column(db.String(50), nullable=False)  # 使用类型：工单使用、维修使用、测试使用等
    user_name = db.Column(db.String(100), nullable=False)  # 使用人姓名
    usage_date = db.Column(db.DateTime, default=datetime.utcnow)
    purpose = db.Column(db.String(200), nullable=False)  # 使用目的
    notes = db.Column(db.Text)  # 备注

    material = db.relationship('Material', backref=db.backref('usages', lazy=True))
    work_order = db.relationship('WorkOrder', backref=db.backref('material_usages', lazy=True))
    user = db.relationship('User', backref=db.backref('material_usages', lazy=True))

    def to_dict(self):
        unit_price = self.material.unit_price if self.material else 0
        total_price = unit_price * self.quantity if unit_price else 0
        return {
            'id': self.id,
            'usage_id': self.id,  # 添加usage_id字段用于前端删除操作
            'material_id': self.material_id,
            'material_name': self.material.name if self.material else None,
            'material_code': self.material.code if self.material else None,
            'material_specification': self.material.specification if self.material else None,
            'material_unit': self.material.unit if self.material else None,
            'unit_price': unit_price,
            'total_price': round(total_price, 2),
            'work_order_id': self.work_order_id,
            'user_id': self.user_id,
            'user_name': self.user_name,  # 使用存储的用户姓名
            'usage_type': self.usage_type,
            'quantity': self.quantity,
            'usage_date': self.usage_date.isoformat() if self.usage_date else None,
            'purpose': self.purpose,
            'notes': self.notes
        }
